package com.example.asuper.check.Db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import com.example.asuper.check.Helper.*;
import com.example.asuper.check.Model.CheckModel;
import com.example.asuper.check.Model.TitleMessageModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Super on 2015/12/27.
 */
public class CheckDAL implements CheckDbService {
    private DbOpenHelper mHelper = null;
    private String SpliteCode;
    public CheckDAL(Context context) {
        mHelper = new DbOpenHelper(context);
        SpliteCode= SharePrefenceHelper.ReadSharedPreferences("splite_info","SPLITE",context);
    }

    //添加数据
    @Override
    public boolean addCheckData(CheckModel model) {
        boolean result = false;
        SQLiteDatabase database = null;
        try {
            String sql = "insert into asmcheck(code,name,msg,state,time,checkuser) values(?,?,?,?,?,?)";
            Object[] params = {model.getCheckCode(), model.getCheckName(), model.getRemark(), model.getState(), StringHelper.getCurrentTime(), model.getmCheckUser()};
            database = mHelper.getWritableDatabase();
            database.execSQL(sql, params);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (database != null) {
                database.close();
            }
        }

        return result;
    }

    //批量添加
    @Override
    public boolean addCheckData(ArrayList<CheckModel> models) {
        boolean result = false;
        SQLiteDatabase database = null;
        try {
            database = mHelper.getWritableDatabase();
            String sql = "insert into asmcheck(code,name,msg,state) values(?,?,?,?)";
            SQLiteStatement stat = database.compileStatement(sql);
            database.beginTransaction();
            for (CheckModel model : models) {
                stat.bindString(1, model.getCheckCode());
                stat.bindString(2, model.getmCheckColums());
                stat.bindString(3, model.getRemark());
                stat.bindString(4, model.getState());
                stat.executeInsert();
            }
            database.setTransactionSuccessful();
            database.endTransaction();
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (database != null) {
                database.close();
            }
        }

        return result;
    }

    //operateType:1.删除单条   2:删除所有
    @Override
    public boolean deleteCheckData(String checkCode, String operateType) {
        boolean result = false;
        SQLiteDatabase database = null;
        try {
            String sql = operateType == "1" ? "delete from asmcheck where code=?" : "delete from asmcheck";
            Object[] params = {checkCode};
            database = mHelper.getWritableDatabase();
            if (operateType == "1") {
                database.execSQL(sql, params);
            } else {
                database.execSQL(sql);
            }
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (database != null) {
                database.close();
            }
        }
        return result;
    }

    //更新数据
    //operateType:1:未盘   2：已盘   3：盘盈   4：删除
    @Override
    public boolean updateCheckData(String checkCode, String operateType) {
        boolean result = false;
        SQLiteDatabase database = null;
        try {
            String sql = "update asmcheck set state=? where code=?";
            Object[] params = {operateType, checkCode};
            database = mHelper.getWritableDatabase();
            database.execSQL(sql, params);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (database != null) {
                database.close();
            }
        }

        return result;
    }

    //保存盘点信息
    //checkcode:资产编号  operateType：暂不用   userName：盘点人
    @Override
    public boolean saveChecked(String checkCode, String operateType, String userName) {
        boolean result = false;
        SQLiteDatabase database = null;
        try {
            String sql = "update asmcheck set state='2',checkuser=?,time=? where code=?";
            Object[] params = { userName, StringHelper.getCurrentTime(), checkCode};
            database = mHelper.getWritableDatabase();
            database.execSQL(sql, params);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (database != null) {
                database.close();
            }
        }

        return result;
    }

    @Override
    public boolean updateRemark(String checkCode, String Remark) {
        boolean result = false;
        SQLiteDatabase database = null;
        try {
            String sql = "update asmcheck set remark=? where code=?";
            Object[] params = { Remark,  checkCode};
            database = mHelper.getWritableDatabase();
            database.execSQL(sql, params);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (database != null) {
                database.close();
            }
        }
        return result;
    }

    //查询数据 ： 单条
    @Override
    public CheckModel getCheckModel(String checkCode) {
        CheckModel checkModel = null;
        SQLiteDatabase database = null;
        try {
            String sql = "select * from asmcheck where code=?";
            String[] params = {checkCode};
            database = mHelper.getReadableDatabase();
            Cursor cursor = database.rawQuery(sql, params);
            while (cursor.moveToNext()) {
                checkModel = new CheckModel();
                checkModel.setCheckId(cursor.getString(cursor.getColumnIndex("id")));
                checkModel.setCheckCode(cursor.getString(cursor.getColumnIndex("code")));
                checkModel.setCheckName(cursor.getString(cursor.getColumnIndex("name")));
                checkModel.setRemark(cursor.getString(cursor.getColumnIndex("msg")));
                checkModel.setState(cursor.getString(cursor.getColumnIndex("state")));
                checkModel.setmCheckMemo(cursor.getString(cursor.getColumnIndex("remark")));
                checkModel.setmTime(cursor.getString(cursor.getColumnIndex("time")));
                checkModel.setmCheckUser(cursor.getString(cursor.getColumnIndex("checkuser")));
            }
            cursor.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (database != null) {
                database.close();
            }
        }

        return checkModel;
    }

    //查询数据：全部
    //operateType 0:所有   1:未盘   2：已盘   3：盘盈   4：删除
    @Override
    public ArrayList<CheckModel> getCheckList(String operateType) {
        ArrayList<CheckModel> checkList = new ArrayList<CheckModel>();
        SQLiteDatabase database = null;
        try {
            String sql = operateType.equals("0") ? "select * from asmcheck" : "select * from asmcheck where state=?";

            String[] params = {operateType};
            database = mHelper.getReadableDatabase();
            Cursor cursor = database.rawQuery(sql, operateType.equals("0") ? null : params);
            CheckModel checkModel = null;
            while (cursor.moveToNext()) {
                checkModel = new CheckModel();
                checkModel.setCheckId(cursor.getString(cursor.getColumnIndex("id")));
                checkModel.setCheckCode(cursor.getString(cursor.getColumnIndex("code")));
                checkModel.setCheckName(cursor.getString(cursor.getColumnIndex("name")));
                checkModel.setRemark(cursor.getString(cursor.getColumnIndex("msg")));
                checkModel.setState(cursor.getString(cursor.getColumnIndex("state")));
                checkModel.setmCheckMemo(cursor.getString(cursor.getColumnIndex("remark")));
                checkModel.setmTime(cursor.getString(cursor.getColumnIndex("time")));
                checkModel.setmCheckUser(cursor.getString(cursor.getColumnIndex("checkuser")));
                checkList.add(checkModel);
            }
            cursor.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (database != null) {
                database.close();
            }
        }
        return checkList;
    }

    @Override
    public ArrayList<CheckModel> getOutList(String operateType) {
        ArrayList<CheckModel> checkList = new ArrayList<CheckModel>();
        SQLiteDatabase database = null;
        try {
            String sql =  "select * from asmcheck where state in(2,3)";

            //String[] params = {operateType};
            database = mHelper.getReadableDatabase();
            Cursor cursor = database.rawQuery(sql, null);
            CheckModel checkModel = null;
            while (cursor.moveToNext()) {
                checkModel = new CheckModel();
                checkModel.setCheckId(cursor.getString(cursor.getColumnIndex("id")));
                checkModel.setCheckCode(cursor.getString(cursor.getColumnIndex("code")));
                checkModel.setCheckName(cursor.getString(cursor.getColumnIndex("name")));
                checkModel.setRemark(cursor.getString(cursor.getColumnIndex("msg")));
                checkModel.setState(cursor.getString(cursor.getColumnIndex("state")));
                checkModel.setmCheckMemo(cursor.getString(cursor.getColumnIndex("remark")));
                checkModel.setmTime(cursor.getString(cursor.getColumnIndex("time")));
                checkModel.setmCheckUser(cursor.getString(cursor.getColumnIndex("checkuser")));
                checkList.add(checkModel);
            }
            cursor.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (database != null) {
                database.close();
            }
        }
        return checkList;
    }

    //根据条件获取列表信息
    //operateType 0:所有   1:未盘   2：已盘   3：盘盈   4：删除
    //searchType  0:全局查询 1:根据编号查询
    //searchMsg   查询条件
    @Override
    public ArrayList<CheckModel> getCheckList(String operateType, String searchType, String searchMsg) {
        ArrayList<CheckModel> checkList = new ArrayList<CheckModel>();
        SQLiteDatabase database = null;
        try {
            String sql = operateType.equals("0") ? "select * from asmcheck" : "select * from asmcheck where state=?";
            if (searchType.equals("1")) {
                sql += " and code='" + searchMsg + "' ";
            }
            if (searchType.equals("0")) {
                sql += " and (code like '%" + searchMsg + "%' or msg like '%" + searchMsg + "%' )";
            }
            String[] params = {operateType};
            database = mHelper.getReadableDatabase();
            Cursor cursor = database.rawQuery(sql, params);
            CheckModel checkModel = null;
            while (cursor.moveToNext()) {
                checkModel = new CheckModel();
                checkModel.setCheckId(cursor.getString(cursor.getColumnIndex("id")));
                checkModel.setCheckCode(cursor.getString(cursor.getColumnIndex("code")));
                checkModel.setCheckName(cursor.getString(cursor.getColumnIndex("name")));
                checkModel.setRemark(cursor.getString(cursor.getColumnIndex("msg")));
                checkModel.setState(cursor.getString(cursor.getColumnIndex("state")));
                checkModel.setmCheckMemo(cursor.getString(cursor.getColumnIndex("remark")));
                checkModel.setmTime(cursor.getString(cursor.getColumnIndex("time")));
                checkModel.setmCheckUser(cursor.getString(cursor.getColumnIndex("checkuser")));
                checkList.add(checkModel);
            }
            cursor.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (database != null) {
                database.close();
            }
        }
        return checkList;
    }

    //获取头部统计信息
    @Override
    public TitleMessageModel getTitleMessage() {
        TitleMessageModel msg = new TitleMessageModel();
        SQLiteDatabase database = null;
        try {
            String sql = "select state,count(state) as count from asmcheck group by state";
            database = mHelper.getReadableDatabase();
            Cursor cursor = database.rawQuery(sql, null);

            while (cursor.moveToNext()) {
                if (cursor.getString(cursor.getColumnIndex("state")).equals("2")) {
                    msg.setCheckedCount(cursor.getString(cursor.getColumnIndex("count")));
                }
                if (cursor.getString(cursor.getColumnIndex("state")).equals("1")) {
                    msg.setUncheckCount(cursor.getString(cursor.getColumnIndex("count")));
                }
                if (cursor.getString(cursor.getColumnIndex("state")).equals("3")) {
                    msg.setOverageCount(cursor.getString(cursor.getColumnIndex("count")));
                }
            }
            cursor.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (database != null) {
                database.close();
            }
        }
        return msg;
    }

    //array转map
    @Override
    public List<Map<String, String>> convertToMapList(ArrayList<CheckModel> list) {
        List<Map<String, String>> listResult = new ArrayList<Map<String, String>>();
        if (list == null) {
            return null;
        }
        Map<String, String> map;
        for (CheckModel model : list) {
            map = new HashMap<String, String>();
            map.put("pcode", model.getCheckCode().trim());
            String columName = "";
            String columValue = "";
            if (model.getCheckName() != null && model.getCheckName().trim() != "") {
                columName = model.getCheckName();

            } else {
                map.put("column1", "字段1");
                map.put("column2", "字段2");
                map.put("column3", "字段3");
                map.put("column4", "字段4");
                map.put("msg1", "");
                map.put("msg2", "");
                map.put("msg3", "");
                map.put("msg4", "");
            }
            if (!columName.equals("")) {
                String[] colums = columName.split(SpliteCode);
                for (int i = 1; i <= 4; i++) {
                    if (i <= colums.length) {
                        map.put("column" + i, colums[i - 1]);
                    } else {
                        map.put("column" + i, "");
                    }
                }
            }
            if (model.getRemark() != null && model.getRemark().trim() != "") {
                columValue = model.getRemark();//.split("\\|")[0]);
            }
            if (!columValue.equals("")) {
                String[] values = columValue.split(SpliteCode);
                for (int i = 1; i <= 4; i++) {
                    if (i <= values.length) {
                        map.put("msg" + i, values[i - 1]);
                    } else {
                        map.put("msg" + i, "");
                    }
                }
            }

            map.put("pstate", ConvertHelper.getStateName(model.getState()));
            listResult.add(map);
        }
        return listResult;
    }

    //输出文本转换
    @Override
    public String getOutStr(ArrayList<CheckModel> list) {
        if (list == null || list.size() <= 0) {
            return "";
        }
        //String contentResult = "资产编号|状态\r\n";
        String contentResult = "";
        try {
            for (CheckModel model : list) {
                String[] time=  model.getmTime().split(" ");
                contentResult += model.getCheckCode() +StringHelper.getSpliteM(SpliteCode) + time[0] +StringHelper.getSpliteM(SpliteCode)+ time[1]+StringHelper.getSpliteM(SpliteCode)+ "\r\n";
            }
        } catch (Exception e) {
            return "baf86762-e9ae-11e5-ba68-b083fe9dbac0";
        }
        return contentResult;
    }


}
